package com.lb.mq;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
@Component
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Lazy, @Autowired})
public class OrderTransactionListener implements TransactionListener {

    private final OrderService orderService;

    // 执行本地事务（发送半消息后调用）
    @Override
    public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        try {
            String orderId = new String(msg.getBody(), StandardCharsets.UTF_8);
            log.info("执行本地事务，订单ID: {}", orderId);

            // 执行本地事务（如插入订单表）
            boolean success = orderService.createOrder(orderId);
            return success ? LocalTransactionState.COMMIT_MESSAGE : LocalTransactionState.ROLLBACK_MESSAGE;

        } catch (Exception e) {
            log.error("本地事务异常: {}", e.getMessage());
            return LocalTransactionState.UNKNOW;
        }
    }

    // Broker 发起事务回查时调用（本地事务返回 UNKNOW 时触发）
    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
        String orderId = new String(messageExt.getBody(), StandardCharsets.UTF_8);
        log.warn("回查事务状态，订单ID: {}", orderId);

        // 重新查询订单是否成功
        boolean exists = orderService.checkOrderExists(orderId);
        return exists ? LocalTransactionState.COMMIT_MESSAGE : LocalTransactionState.ROLLBACK_MESSAGE;
    }

}
